package com.example.notepadapp;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.notepadapp.adapter.DataListAdapter;
import com.example.notepadapp.been.Notepad;
import com.example.notepadapp.databinding.ActivityMainBinding;
import com.example.notepadapp.db.DatabaseHelper;
import com.example.notepadapp.ui.EditActivity;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    public DatabaseHelper databaseHelper;
    SQLiteDatabase db;
    DataListAdapter dataListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = com.example.notepadapp.databinding.ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        databaseHelper = new DatabaseHelper(this);
        db = databaseHelper.getWritableDatabase();
        dataListAdapter = new DataListAdapter();

        // 跳转窗体
//        binding.ivAdd.setOnClickListener(view -> startActivity(new Intent(MainActivity.this, EditActivity.class)));
        binding.ivAdd.setOnClickListener(view -> startActivityForResult(new Intent(MainActivity.this, EditActivity.class), 100));
        // RecyclerView绑定dataListAdapter
        binding.rvList.setAdapter(dataListAdapter);
        // 添加分割线
        binding.rvList.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        binding.rvList.setLayoutManager(new LinearLayoutManager(this));

        findAll();
    }

    // 刷新数据
    public void findAll() {
        List<Notepad> notepadList = databaseHelper.findAll();
        dataListAdapter.update(notepadList);
    }

    // 页面重新可见时，刷新数据
    @Override
    protected void onResume() {
        super.onResume();
        findAll();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 100){
            // 收到新增成功信号，刷新数据
            findAll();
        }
    }
}